//
//  MineViewController.m
//  NBTripe
//
//  Created by Lee on 16/1/7.
//  Copyright © 2016年 Lee. All rights reserved.
//

#import "MineViewController.h"
#import "MineTableViewCell.h"
#import "shouCangTableView.h"
#import "CustomTableViewCell.h"
#import "RecommendCustomViewController.h"
#import "MineViewController.h"
@interface MineViewController ()<UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, strong) UITableView *tableView;

@property (nonatomic, strong) shouCangTableView *storageTableview;

@end

@implementation MineViewController

- (void)viewDidLoad {

   self.title = @"我的";
    self.view.userInteractionEnabled = YES;
   self.view.backgroundColor = [UIColor whiteColor];
    [self createTableView];

   
}
/**
 *  创建tableview
 */
-(void) createTableView{
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, WIDTH,HIGHT) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor clearColor];
    self.tableView.separatorStyle =  UITableViewCellSeparatorStyleNone;
    [self.tableView registerClass:[MineTableViewCell class] forCellReuseIdentifier:@"MineTableViewCell"];
    UIImageView *headImageview = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, 200*XHIGHT)];
    headImageview.image = [UIImage imageNamed:@"mebackground"];
    self.tableView.tableHeaderView = headImageview;
    [self.view addSubview:self.tableView];
}
/**
 *  收藏tableView
 */
- (shouCangTableView *)storageTableview {
    if(!_storageTableview) {
       self.storageTableview = [[shouCangTableView alloc]initWithFrame:CGRectMake(0,64 + 330 * XHIGHT, self.view.frame.size.width, 0) style:UITableViewStylePlain];
        //点击收藏cell进入页面
        void (^block)(NSString *) = ^(NSString *strid) {
            RecommendCustomViewController *customVC = [[RecommendCustomViewController alloc] init];
            customVC.joinedId = strid;
            [self.navigationController pushViewController:customVC animated:YES];
        };
        self.storageTableview.skipBlock = block;
        [self.view addSubview:self.storageTableview];
    }
    return _storageTableview;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return 3;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    MineTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MineTableViewCell"];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
    if (indexPath.row == 0) {
        cell.label.text = @"夜间模式";
        cell.cellImage.image = [UIImage imageNamed:@"yejian"];
    }
    if (indexPath.row == 1) {
        cell.label.text = @"清除缓存";
        cell.cellImage.image = [UIImage imageNamed:@"qingchu"];
        
    }
    if (indexPath.row == 2) {
        cell.label.text = @"我的收藏";
        cell.cellImage.image = [UIImage imageNamed:@"soucang"];
        
    }
    return cell;
  
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.row == 1) {
        [self buttonDidPress];
    }
    if (indexPath.row == 2) {
     
        if (self.storageTableview.frame.size.height == 0) {
            [UIView transitionWithView:self.storageTableview duration:0.5 options:UIViewAnimationOptionTransitionCurlUp animations:^{
                self.storageTableview.frame =  CGRectMake(0, 64 + 330 * XHIGHT, self.view.frame.size.width, 240 * XHIGHT);
               
            } completion:^(BOOL finished) {
            }];
        } else
            [UIView transitionWithView:self.storageTableview duration:0.5 options:UIViewAnimationOptionTransitionCurlUp animations:^{
                self.storageTableview.frame =  CGRectMake(5, 64 + 304* XHIGHT, self.view.frame.size.width - 10 * XWIDTH, 0);
            } completion:^(BOOL finished) {
            }];
    }

}
//将要出现的时候刷新
- (void)viewWillAppear:(BOOL)animated {
    //刷新
    
   self.storageTableview.manager = [CoreDataManager shareManager];
    self.storageTableview.storageArr = [NSArray arrayWithArray:[Convenience selectLocalCoreDataWithManager:self.storageTableview.manager]];
    [self.storageTableview reloadData];
}
//将要消失的时候收回收藏tableview
- (void)viewWillDisappear:(BOOL)animated{
    self.storageTableview.frame = CGRectMake(0, 0, 0, 0);
}




-(void)buttonDidPress {
    //获取完整路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSString *text = [NSString stringWithFormat:@"清理%.2fM的缓存好不好？☺️",[self folderSizeAtPath:path]];
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"清理缓存" message:text preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"听你的，么么哒" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        [self cleanAction];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"就不呢" style:UIAlertActionStyleCancel handler:nil];
    [alert addAction:cancelAction];
    [alert addAction:okAction];
    [self presentViewController:alert animated:YES completion:nil];
}

#pragma mark - 清空
-(void)cleanAction
{
    //获取完整路径
    NSString *path = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES).lastObject;
    path = [path stringByAppendingPathComponent:@"Caches"];
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        NSArray *fileNameAarray = [manager subpathsAtPath:path];
        for (NSString *fileName in fileNameAarray) {
            //拼接绝对路径
            NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
            
            //通过文件管理者删除文件
            [manager removeItemAtPath:absolutePath error:nil];
        }
    }
}


#warning 计算单个文件大小的方法
-(long long)fileSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if ([manager fileExistsAtPath:path]) {
        return [[manager attributesOfItemAtPath:path error:nil]fileSize];
    }
    return 0;
}
#warning  计算一个文件夹的大小
-(float)folderSizeAtPath:(NSString *)path
{
    NSFileManager *manager = [NSFileManager defaultManager];
    if (![manager fileExistsAtPath:path]) {
        return 0;
    }
    //根据路径获取文件夹里面元素集合
    //获取集合类型的枚举类型
    NSEnumerator *enumeratot = [[manager subpathsAtPath:path] objectEnumerator];
    //每次遍历得到的文件名
    //文件夹的大小
    NSString *fileName = [NSString string];
    float folderSize = 0;
    while ((fileName = [enumeratot nextObject])!= nil) {
        NSString *absolutePath = [path stringByAppendingPathComponent:fileName];
        folderSize += [self fileSizeAtPath:absolutePath];
    }
    return folderSize/(1024*1024.0);
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
